package com.tianci.appstore.ui.list.cgylist;

import android.content.Context;
import android.content.Intent;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.coocaa.x.framework.utils.Android;
import com.coocaa.x.framework.utils.LogUtils;
import com.paster.util.JsonUtil;
import com.tianci.appstore.R;
import com.tianci.appstore.audio.IAudioMatchListener;
import com.tianci.appstore.controller.AppStoreAppListController;
import com.tianci.appstore.ui.control.BaseUIController;
import com.tianci.appstore.ui.data.SkyAppDetailData.AppStatus;
import com.tianci.appstore.ui.data.SkyCategoryData;
import com.tianci.appstore.ui.data.SkyListAppData;
import com.tianci.appstore.ui.list.ListBlock.MuitlSelectionListener;
import com.tianci.appstore.ui.list.ListFlipper;
import com.tianci.appstore.ui.list.ListStatusBlock;
import com.tianci.appstore.ui.list.SkyListAdapter;
import com.tianci.appstore.ui.list.SkyListAdapter.OnItemClickListener;
import com.tianci.appstore.ui.list.manage.MultiSelectUIListener;
import com.tianci.appstore.ui.widget.SkyAppPager.AnimListener;
import com.tianci.appstore.ui.widget.SkyBaseItemView;
import com.tianci.appstore.ui.widget.SkyBaseItemView.OnAppKeyListener;
import com.tianci.appstore.ui.widget.SkyCustomLayout;
import com.tianci.appstore.ui.widget.SkyGridAdapter;

import org.json.JSONException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;

public class ListOperationController extends BaseUIController implements MuitlSelectionListener,
        OnAppKeyListener, AnimListener, OnItemClickListener {
    protected int row;          // 3
    protected int column;       // 4
    protected int pageSize;     // 12
    protected int totalCount;
    protected int direction;
    protected int posY;
    protected List<SkyListAppData> multiSelectDataList = new ArrayList<SkyListAppData>();

    protected TextView pageNumberText;
    protected ImageView leftArrow, rightArrow;
    protected SkyCategoryData cgyData;

    protected MultiSelectUIListener uiListener;
    private IAudioMatchListener mAudioMatchListener = null;

    public ListOperationController(Context context, ListFlipper flipper, int row, int column) {
        super(context);
        this.mPager = flipper;
        this.row = row;
        this.column = column;
        this.pageSize = row * column;

        flipper.setAnimListener(this);
    }

    public void setFlipper(ListFlipper flipper) {
        this.mPager = flipper;
    }

    @Override
    public boolean onMultiSelectChanged(SkyListAppData data, boolean selected) {
        // TODO Auto-generated method stub
        if (selected) {
            if (!multiSelectDataList.contains(data))
                multiSelectDataList.add(data);
        } else {
            if (multiSelectDataList.contains(data))
                multiSelectDataList.remove(data);
        }
        if (uiListener != null)
            uiListener.OnSelectCountChanged(multiSelectDataList.size());
        return true;
    }

    public void setAudioMatchListener(IAudioMatchListener listener) {
        this.mAudioMatchListener = listener;
    }

    public void setMultiSelectUIListener(MultiSelectUIListener uiListener) {
        this.uiListener = uiListener;
    }

    @Override
    public List<SkyListAppData> getSelectedDataList() {
        return multiSelectDataList;
    }

    @Override
    public void setSelectedDataList(List<SkyListAppData> selList) {
        // TODO Auto-generated method stub
        this.multiSelectDataList = selList;
    }

    public void clearSelectedDataList() {
        multiSelectDataList.clear();
    }

    @Override
    public boolean onKeyDown(int keyCode, int index, boolean[] turnPage) {
        // TODO Auto-generated method stub
        if (index % column == 0 && keyCode == KeyEvent.KEYCODE_DPAD_LEFT) {
            if (mCurrentPage > 0) {
                direction = keyCode;
                int oldIndex = mPager.getDisplayedChild();
                mPager.displayPrePage();
                mCurrentPage--;
                posY = index / column;
                refreshPageNumber();

                if (mCurrentPage > 0 && mCurrentPage < mTotalPage - 1) {
                    int lastIndex = (oldIndex + 1) % ListFlipper.VIEW_PAGE_COUNT;
                    SkyCustomLayout lastLayout = (SkyCustomLayout) mPager.getChildAt(lastIndex);
                    SkyListAdapter adapter = (SkyListAdapter) lastLayout.getAdapter();
                    adapter.clearData(mCurrentPage - 1, pageSize);
                }
                requestUnloadData();
                return true;
            }
            //else 
            //mPager.hitBoundary(keyCode);
        } else if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) {
            if (mCurrentPage < mTotalPage - 1) {
                if (index % column == column - 1) {
                    direction = keyCode;
                    int oldIndex = mPager.getDisplayedChild();
                    mPager.displayNextPage();
                    mCurrentPage++;
                    posY = index / column;
                    refreshPageNumber();

                    if (mCurrentPage > 0 && mCurrentPage < mTotalPage - 1) {
                        int firstIndex = (oldIndex + ListFlipper.VIEW_PAGE_COUNT - 1) % ListFlipper.VIEW_PAGE_COUNT;
                        SkyCustomLayout firstLayout = (SkyCustomLayout) mPager.getChildAt(firstIndex);
                        SkyListAdapter adapter = (SkyListAdapter) firstLayout.getAdapter();
                        adapter.clearData(mCurrentPage + 1, getCountByIndex(mCurrentPage + 1));
                    }
                    requestUnloadData();
                    return true;
                }
            } else {
                SkyCustomLayout child = (SkyCustomLayout) mPager.getCurrentView();
                if (index >= child.getChildCount() - 1 || index % column == column - 1) {
                    // mPager.hitBoundary(keyCode);
                    return true;
                }
            }
        }
        return false;
    }

    private void requestUnloadData() {
        SkyCustomLayout child;
        SkyListAdapter adapter;
        for (int i = 0; i < mPager.getChildCount(); i++) {
            child = (SkyCustomLayout) mPager.getChildAt(i);
            adapter = (SkyListAdapter) child.getAdapter();
            if (!adapter.isDataFilled()) {
                int index = adapter.getPageIndex();
                if (index >= 0 && index < mTotalPage)
                    AppStoreAppListController.getInstance().getAppList(cgyData.id, index + 1, pageSize);
            }
        }
    }

    protected void refreshPageNumber() {
        if (pageNumberText != null)
            pageNumberText.setText(String.format("%d/%d%s(%d%s)",
                    (mCurrentPage + 1), mTotalPage, mContext.getResources().getString(R.string.page),
                    totalCount, mContext.getResources().getString(R.string.app_count_str)));
        if (mCurrentPage > 0) {
            leftArrow.setVisibility(View.VISIBLE);
        } else {
            leftArrow.setVisibility(View.INVISIBLE);
        }
        if (mCurrentPage < mTotalPage - 1) {
            rightArrow.setVisibility(View.VISIBLE);
        } else {
            rightArrow.setVisibility(View.INVISIBLE);
        }
    }

    @Override
    public boolean onAnimStart(int current) {
        // TODO Auto-generated method stub
        SkyBaseItemView.mKey = false;
        return false;
    }

    @Override
    public boolean onAnimEnd(int current) {
        // TODO Auto-generated method stub
        SkyBaseItemView.mKey = true;
        if (direction == KeyEvent.KEYCODE_DPAD_RIGHT) {
            SkyCustomLayout layer = (SkyCustomLayout) mPager.getChildAt(mPager.getDisplayedChild());
            int index = posY * column;
            if (index >= layer.getChildCount())
                index = (layer.getChildCount() - 1) / column * column;
            layer.setFocusPos(index, true);
        } else if (direction == KeyEvent.KEYCODE_DPAD_LEFT) {
            SkyCustomLayout layer = (SkyCustomLayout) mPager.getChildAt(mPager.getDisplayedChild());
            int index = (posY + 1) * column - 1;
            if (index >= layer.getChildCount())
                index = layer.getChildCount() - 1;
            layer.setFocusPos(index, true);
        }
        if (dataCan.size() > 0) {
            Iterator iter = dataCan.entrySet().iterator();
            while (iter.hasNext()) {
                Entry entry = (Entry) iter.next();
                int key = (Integer) entry.getKey();
                List<SkyListAppData> value = (List<SkyListAppData>) entry.getValue();
                refreshPage(key, value);
            }
            dataCan.clear();
        }
        return false;
    }

    public void setPageNoView(TextView text, ImageView leftArrow, ImageView rightArrow) {
        this.pageNumberText = text;
        this.leftArrow = leftArrow;
        this.rightArrow = rightArrow;
    }

    protected HashMap dataCan = new HashMap<Integer, List<SkyListAppData>>();

    public void refreshPage(int pageIndex, List<SkyListAppData> appList) {
        if (!SkyBaseItemView.mKey) {
            dataCan.put(pageIndex, appList);
            return;
        }
        for (int i = 0; i < ListFlipper.VIEW_PAGE_COUNT; i++) {
            SkyCustomLayout child = (SkyCustomLayout) mPager.getChildAt(i);
            SkyListAdapter adapter = (SkyListAdapter) child.getAdapter();
            if (adapter.getPageIndex() == pageIndex && !adapter.isDataFilled()) {
                adapter.setData(pageIndex, appList);
            }
        }
    }

    private void requestUnloadDataFirst() {
        SkyCustomLayout child = (SkyCustomLayout) mPager.getCurrentView();
        SkyListAdapter adapter = (SkyListAdapter) child.getAdapter();
        if (!adapter.isDataFilled()) {
            int index = adapter.getPageIndex();
            if (index >= 0 && index < mTotalPage) {
                LogUtils.d("list", "requesting unloadDataFirst, pageIndex = " + (index + 1));
                AppStoreAppListController.getInstance().getAppList(cgyData.id, index + 1, pageSize);
            }
        }
//        for(int i = 0; i < flipper.getChildCount(); i++)
//        {
//            child = (SkyCustomLayout) flipper.getChildAt(i);
//            adapter = (SkyListAdapter) child.getAdapter();
//            if(!adapter.isDataFilled())
//            {
//                int index = adapter.getPageIndex();
//                if(index >= 0 && index < pageCount)
//                {
//                    LogUtils.d("list", "requesting unloadDataFirst, pageIndex = "+(index+1));
//                    AppStoreAppListController.getInstance(mContext).getAppList(cgyData.id, index + 1, pageSize);
//                }
//            }
//        }
    }

    public void setCategoryData(SkyCategoryData data, int pageIndex) {
        this.cgyData = data;
        initAppCount(data.totalCount, pageIndex);

        int index = pageIndex - 1;
        int displayChild = 1;
        if (index < 0) {
            index = 0;
            displayChild = 0;
        } else if (index >= mTotalPage - 2) {
            index = pageIndex - 2;
            displayChild = 2;
        }
        for (int i = 0; i < ListFlipper.VIEW_PAGE_COUNT && i < mTotalPage; i++) {
            SkyCustomLayout child = (SkyCustomLayout) mPager.getChildAt(i);
            SkyListAdapter adapter = (SkyListAdapter) child.getAdapter();
            adapter.clearData(index + i, getCountByIndex(index + i));
        }
        mPager.setInAnimation(null);
        mPager.setOutAnimation(null);
        mPager.setDisplayedChild(displayChild);
        requestUnloadDataFirst();
    }

    protected void initAppCount(int totalCount, int pageIndex) {
        this.totalCount = totalCount;
        this.mTotalPage = totalCount / (row * column);
        if (totalCount % (row * column) != 0)
            this.mTotalPage++;
        if (pageIndex < 0 || pageIndex >= mTotalPage)
            pageIndex = 0;
        this.mCurrentPage = pageIndex;
        refreshPageNumber();
    }

    // 点击二级分类时，刷新分类数据
    public void setCategoryData(SkyCategoryData data, int pageIndex, boolean animLeft) {
        direction = KeyEvent.KEYCODE_DPAD_RIGHT;
        posY = 0;
        if (animLeft)
            mPager.displayPrePage();
        else
            mPager.displayNextPage();

        this.cgyData = data;
        this.totalCount = data.totalCount;
        this.mTotalPage = totalCount / (row * column);
        if (totalCount % (row * column) != 0)
            this.mTotalPage++;
        if (pageIndex < 0 || pageIndex >= mTotalPage)
            pageIndex = 0;
        this.mCurrentPage = pageIndex;
        refreshPageNumber();

        int displayChild = mPager.getDisplayedChild();
        SkyCustomLayout child = (SkyCustomLayout) mPager.getChildAt(displayChild);
        SkyListAdapter adapter = (SkyListAdapter) child.getAdapter();
        adapter.clearData(pageIndex, getCountByIndex(pageIndex));

        SkyListAdapter leftAdapter = getAdapter(displayChild, true);
        SkyListAdapter rightAdapter = getAdapter(displayChild, false);

        if (mTotalPage <= 1) {
            leftAdapter.clearData(-100, 0);
            rightAdapter.clearData(-101, 0);
            requestUnloadData();
            return;
        }

        if (pageIndex >= 1) {
            leftAdapter.clearData(pageIndex - 1, pageSize);
            if (pageIndex < mTotalPage - 1) {
                rightAdapter.clearData(pageIndex + 1, getCountByIndex(pageIndex + 1));
            } else
                rightAdapter.clearData(-101, 0);
        } else {
            leftAdapter.clearData(-100, 0);
            rightAdapter.clearData(pageIndex + 1, getCountByIndex(pageIndex + 1));
        }

        requestUnloadDataFirst();
    }

    private SkyListAdapter getAdapter(int centerIndex, boolean left) {
        int childIndex = 0;
        if (left)
            childIndex = (centerIndex + ListFlipper.VIEW_PAGE_COUNT - 1) % ListFlipper.VIEW_PAGE_COUNT;
        else
            childIndex = (centerIndex + 1) % ListFlipper.VIEW_PAGE_COUNT;

        SkyCustomLayout child = (SkyCustomLayout) mPager.getChildAt(childIndex);
        SkyListAdapter adapter = (SkyListAdapter) child.getAdapter();
        return adapter;
    }

    protected int getCountByIndex(int index) {
        if (index < mTotalPage - 1)
            return pageSize;
        else if (index == mTotalPage - 1) {
            if (totalCount % pageSize == 0)
                return pageSize;
            else
                return totalCount % pageSize;
        }
        return 0;
    }

    public int getCurrentPageIndex() {
        return mCurrentPage;
    }

    public void updateAppStatus(String pkgName, AppStatus status) {
        for (int i = 0; i < ListFlipper.VIEW_PAGE_COUNT; i++) {
            SkyCustomLayout child = (SkyCustomLayout) mPager.getChildAt(i);
            for (View view : child.getChildViews()) {
                ListStatusBlock block = (ListStatusBlock) view;
                if (block.getPkgName() != null && block.getPkgName().equals(pkgName)) {
                    block.updateStatus(status);
                }
            }
        }
    }

    @Override
    public void onBlockClicked(View v, SkyListAppData data, int index) {
        // TODO Auto-generated method stub
    }


    @Override
    public String getCommand() {
        String json = "";
        try {
            HashMap<String, String[]> command = getGlobalCommand();
            HashMap<String, String[]> fluzz = new HashMap<String, String[]>();
            if (mAudioMatchListener != null) {
                command = mAudioMatchListener.addExtraCommand(command);
            }
            addCategoryCommand(command);
            if (mButtonLayer != null) {
                command.put("下载管理", new String[]{"下载管理"});
            }
            command.put("nextpage", new String[]{"下一页"});
            command.put("prepage", new String[]{"上一页"});
            addItemCommand(command);
            json = JsonUtil.makeScenceJson(
                    getScene(), command, fluzz, null)
                    .toString();
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return json;
    }

    @Override
    public String getScene() {
        // TODO Auto-generated method stub
        return "com.tianci.appstore:AppListActivity";
    }

    @Override
    public boolean exeCommand(Intent intent) {
        if (intent.hasExtra("_scene")
                && intent.getStringExtra("_scene").equals(
                getScene())) {
            if (intent.hasExtra("_command")) {

                String command = intent.getStringExtra("_command");
                LogUtils.d("luwei", "the command is " + command);
                int index = getIndexByCategoryName(command);
                if (index >= 0) {
                    mCategoryBar.setClickPos(index);
                    return true;
                }
                Android.simulateKey(KeyEvent.KEYCODE_BACK, 0);
                if (((SkyGridAdapter) getCurrentPage().getAdapter()).audioMatch(command)) {
                    return true;
                }
                if (command.equals("下载管理")) {
                    mButtonLayer.audioMatch(intent.getStringExtra(command));
                    return true;
                } else if (command.equals("nextpage")) {
                    onKeyDown(KeyEvent.KEYCODE_DPAD_RIGHT, column - 1, new boolean[]{false, false, true, false});
                    return true;
                } else if (command.equals("prepage")) {
                    onKeyDown(KeyEvent.KEYCODE_DPAD_LEFT, 0, new boolean[]{true, false, false, false});
                    return true;
                } else if (super.exeCommand(intent)) {
                    return true;
                } else if (mAudioMatchListener != null) {
                    Android.simulateKey(KeyEvent.KEYCODE_BACK, 0);
                    mAudioMatchListener.onAudioMatch(command);
                    return true;
                }
            }
        }
        return false;
    }
}
